<template>
  <NModal :show="show" @onUpdateShow="close">
    <div ref="modalRef" class="edit-dia">
      <MacHeader
        title="授权"
        :is-fullscreen="isFullscreen"
        :show-desc="false"
        @toggle="toggle"
        @close="close"
      />
      <div class="content">
        <NScrollbar style="max-height: 80vh">
          <div style="padding-left: 5px">
            <NForm ref="formRef" :model="queryForm" :rules="rules">
              <NFormItem label="权限" path="menu_ids">
                <NTree
                  ref="treeRef"
                  show-line
                  cascade
                  checkable
                  selectable
                  :data="options"
                  :default-checked-keys="queryForm.menu_ids"
                  label-field="metaTitle"
                  key-field="id"
                  children-field="children"
                  @update:checked-keys="updateCheckedKeys"
                />
              </NFormItem>
              <NFormItem>
                <div class="tools w-full">
                  <NButton
                    type="primary"
                    attr-type="button"
                    @click="handleValidateClick"
                  >
                    <span>提交</span>
                  </NButton>
                </div>
              </NFormItem>
            </NForm>
          </div>
        </NScrollbar>
      </div>
    </div>
  </NModal>
</template>
<script setup lang="ts">
import { ref, inject } from 'vue'
import { useFullscreen } from '@vueuse/core'
import type { FormInst, FormRules } from 'naive-ui'
import {
  NButton,
  useMessage,
  NModal,
  NForm,
  NFormItem,
  NTree,
  NScrollbar
} from 'naive-ui'
import type { TreeSelectOption } from 'naive-ui'
import roleApi from '@/service/api/setting/role'
import routerApi from '@/service/api/router'
import MacHeader from '@/components/codeBlock/MacHeader'
const $clone = inject('$clone') as <T>(data: T) => T
const modalRef = ref()
const { isFullscreen, toggle } = useFullscreen(modalRef)
const show = ref(false)
const toast = useMessage()
const emit = defineEmits(['success'])
const queryForm: any = ref({
  roleName: '',
  roleCode: '',
  menu_ids: []
})
const updateCheckedKeys = (keys: Array<string | number>) => {
  queryForm.value.menu_ids = keys
}
const formRef = ref<FormInst | null>(null)
const rules: FormRules = {
  roleName: [
    {
      required: true,
      message: '请输入菜单名称',
      trigger: 'blur'
    }
  ],
  roleCode: [
    {
      required: true,
      message: '请输入角色Code',
      trigger: 'blur'
    }
  ]
}
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate(errors => {
    if (!errors) {
      save()
    }
  })
}
const treeRef = ref()
const save = async () => {
  if (!queryForm.value.parentId) {
    queryForm.value.parentId = 0
  }
  const params = $clone(queryForm.value)
  params.menu_ids = [
    ...params.menu_ids,
    ...treeRef.value.getIndeterminateData().keys
  ]
  if (params?.id) {
    const { code, message } = await roleApi.edit(params)
    if (code !== 200) {
      toast.error(message)
      return
    }
    toast.success('编辑成功')
  } else {
    const { code, message } = await roleApi.add(params)
    if (code !== 200) {
      toast.error(message)
      return
    }
    toast.success('添加成功')
  }
  emit('success')
  close()
}
const close = () => {
  queryForm.value = {
    roleName: '',
    roleCode: '',
    menu_ids: []
  }
  show.value = false
}
const options = ref<TreeSelectOption[]>([])
const getItem = (el: TreeSelectOption): TreeSelectOption => {
  if (el.children) {
    if (el.children.length > 0) {
      el.children = el.children.map((item: TreeSelectOption) => {
        return getItem(item)
      })
    } else {
      delete el.children
    }
  }
  return el
}
const getLastIds = (el: any) => {
  let ids: number[] = []
  if (el.children && el.children.length > 0) {
    el.children.map((item: TreeSelectOption) => {
      ids = [...ids, ...getLastIds(item)]
    })
  } else {
    ids.push(el.id)
  }
  return ids
}
const open = async (row?: any) => {
  const { data } = await routerApi.allList()
  options.value = data.map((el: TreeSelectOption) => {
    return getItem(el)
  })
  if (row) {
    const itRow = $clone(row)
    const ids: number[] = []
    data.forEach((el: any) => {
      ids.push(...getLastIds(el))
    })
    itRow.menu_ids = itRow.menu_ids.filter((el: number) => {
      return ids.includes(el)
    })
    queryForm.value = itRow
  }
  show.value = true
}

defineExpose({
  open
})
</script>

<style scoped lang="scss"></style>
